import React, { Component } from 'react'
import { Tree } from 'antd'
import T from '../../../../lib/T'
import api from '../../../../api/index'
import { connect } from 'mirrorx'

const TreeNode = Tree.TreeNode

class Demo extends Component {
  constructor (props) {
    super(props)
    this.state = {
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: ['0-0-0'],
      selectedKeys: []
    }
    this.onExpand = this.onExpand.bind(this)
    this.onCheck = this.onCheck.bind(this)
    this.onSelect = this.onSelect.bind(this)
    this.renderTreeNodes = this.renderTreeNodes.bind(this)
    this.getResourcesByRoleId = this.getResourcesByRoleId.bind(this) // 根据角色ID查看菜单权限详情
  }

  onExpand (expandedKeys) {
    // console.log('expandedKeys', expandedKeys)
    this.setState({
      expandedKeys,
      autoExpandParent: false
    })
  }
  componentDidMount () {
    if (this.props.action !== 'add') {
      this.getResourcesByRoleId()
    }
  }
  componentWillReceiveProps (props) {
    // console.log('props', props)
    this.setState({
      expandedKeys: props.parentId
    })
  }
  getResourcesByRoleId () {
    let authorityList = [] // 保存权限ID列表
    let children = [] // 保存子权限ID
    let grandson = [] // 保存孙权限ID
    let url = api.getResourcesByRoleId.path
    let data = {
      roleId: this.props.roleId
    }
    T.ajax({
      url,
      data,
      loading: true,
      method: 'post'
    }).then((res) => {
      console.log('查看权限', res.data)
      if (res.code === 0) {
        res.data.forEach(item => {
          authorityList.push(item.id)
          if (item.child) {
            item.child.forEach(p => {
              if (p.child) {
                p.child.forEach(s => {
                  grandson.push(s.id)
                })
              } else {
                children.push(p.id)
              }
            })
          }
        })
        if (grandson.length > 0) {
          this.setState({
            checkedKeys: [...children, ...grandson]
          })
        } else {
          this.setState({
            checkedKeys: [...children]
          })
        }
      }
    })
  }
  onCheck (checkedKeys, e) {
    let check = checkedKeys
    let parentList = [] // 子权限未全选时父节点的id列表
    console.log('e', e)
    // 未选择View权限时选择Management权限(将View权限也选中)
    if (e.checked && e.node.props.title === 'Management' && check.indexOf((e.node.props.eventKey - 1) + '') === -1) {
      check.push((e.node.props.eventKey - 1) + '')
      parentList = e.halfCheckedKeys.filter(item => { return item !== 'Choose all' })
    }
    // 已选择View权限时选择Management权限
    if (e.checked && e.node.props.title === 'Management' && check.indexOf((e.node.props.eventKey - 1) + '') >= 0) {
      parentList = e.halfCheckedKeys.filter(item => { return item !== 'Choose all' })
    }
    // 选择View权限或者取消Management权限
    if ((e.checked && e.node.props.title === 'View') || ((!e.checked) && e.node.props.title === 'Management')) {
      parentList = e.halfCheckedKeys.filter(item => { return item !== 'Choose all' })
    }
    // Management已钩选时取消View权限(将Management权限也取消钩选)
    if ((!e.checked) && e.node.props.title === 'View') {
      if (check.indexOf((e.node.props.eventKey - 1 + 2) + '') >= 0) {
        check.splice(check.indexOf((e.node.props.eventKey - 1 + 2) + ''), 1)
      }
      parentList = e.halfCheckedKeys.filter(item => { return item !== 'Choose all' })
      parentList.splice(parentList.indexOf((e.node.props.eventKey - 1) + ''), 1)
    }
    console.log('check', check)
    this.setState({ checkedKeys: check })

    if (this.props.action !== 'view') { // 查看和修改权限时将钩选的权限传给父组件
      if (check.indexOf('Choose all') >= 0) {
        check.splice(check.indexOf('Choose all'), 1)// 将全选框的Key值从列表中剔除
        this.props.getResourceList(check, parentList)
      } else {
        this.props.getResourceList(check, parentList)
      }
    }
  }

  onSelect (selectedKeys, info) {
    console.log('info', info)
    // this.setState({ checkedKeys: [...this.state.checkedKeys, ...selectedKeys] })
  }

  renderTreeNodes (data) {
    const { action } = this.props
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode
            title={item.title}
            key={item.key}
            dataRef={item}
            disabled={action === 'view'}
          >

            {this.renderTreeNodes(item.children)}
          </TreeNode>
        )
      }
      return <TreeNode disabled={action === 'view'} {...item} />
    })
  }

  render () {
    let { treeData } = this.props
    // console.log('expandedKeys', this.props.parentId)
    let dataList
    if (this.props.action === 'view') {
      dataList = treeData
    } else {
      dataList = [{
        title: 'Choose all',
        key: 'Choose all',
        children: treeData
      }]
    }
    return (
      <div>
        {treeData && treeData.length > 0
          ? <Tree
            className='authority'
            checkable
            onExpand={this.onExpand}
            expandedKeys={this.state.expandedKeys} // 按需要展开指定的节点
            autoExpandParent={this.state.autoExpandParent}
            onCheck={this.onCheck}
            // defaultExpandedKeys={parentId}
            // defaultExpandAll   //默认展开所有节点
            checkedKeys={this.state.checkedKeys}
            onSelect={this.onSelect}
            selectedKeys={this.state.selectedKeys}
          >
            {this.renderTreeNodes(dataList)}
          </Tree>
          : ''
        }
      </div>

    )
  }
}

export default connect(state => {
  return state.mainModel
})(Demo)
